Skip to content

KAFKA-19160: Improve performance of fetching stable offsets #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: trunk
Choose a base branch
from

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 21, 2025

When fetching stable offsets in the group coordinator, we iterate over
all requested partitions. For each partition, we iterate over the
group's ongoing transactions to check if there is a pending
transactional offset commit for that partition.

This can get slow when there are a large number of partitions and a
large number of pending transactions. Instead, maintain a list of
pending transactions per partition to speed up lookups.

Summary by CodeRabbit

  • New Features

    • Improved tracking of open transactions, now providing more detailed monitoring by group, topic, and partition.
  • Bug Fixes

    • Enhanced accuracy when deleting and checking pending transactional offsets, ensuring more precise offset management.
  • Performance

    • More efficient handling of transactional offset commits and transaction completion, especially for complex scenarios involving multiple topics and partitions.

When fetching stable offsets in the group coordinator, we iterate over
all requested partitions. For each partition, we iterate over the
group's ongoing transactions to check if there is a pending
transactional offset commit for that partition.

This can get slow when there are a large number of partitions and a
large number of pending transactions. Instead, maintain a list of
pending transactions per partition to speed up lookups.
@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

@squah-confluent Thanks for the patch. Could we write a micro benchmark to demonstrate the gain?

Copy link

coderabbitai bot commented Apr 21, 2025

Walkthrough

A new nested data structure was introduced in the OffsetMetadataManager class to track open transactions at the group, topic, and partition level. Several methods were updated to utilize this structure, enabling more granular management of transactional offsets. The changes affect how pending transactional offsets are checked, how offsets are deleted, and how transactional state is replayed and cleaned up. The new structure operates alongside the existing group-level tracking, and relevant methods were adapted to maintain and reference the new nested map accordingly.

Changes

File(s) Change Summary
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java Introduced a nested map to track open transactions by group, topic, and partition; updated methods for offset deletion, replay logic, and pending checks to use the new structure; added a suppression annotation for method complexity.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant OffsetMetadataManager
    participant Storage

    Client->>OffsetMetadataManager: Commit Transactional Offset (group, topic, partition, producerId)
    OffsetMetadataManager->>OffsetMetadataManager: Add producerId to openTransactionsByGroupTopicAndPartition
    OffsetMetadataManager->>Storage: Store transactional offset

    Client->>OffsetMetadataManager: Delete All Offsets (group)
    OffsetMetadataManager->>OffsetMetadataManager: Iterate openTransactionsByGroupTopicAndPartition
    OffsetMetadataManager->>Storage: Add tombstone if no committed offset

    Client->>OffsetMetadataManager: Replay Transactional Offset Commit
    OffsetMetadataManager->>OffsetMetadataManager: Update nested map with producerId

    Client->>OffsetMetadataManager: End Transaction (producerId)
    OffsetMetadataManager->>OffsetMetadataManager: Remove producerId from nested map
    OffsetMetadataManager->>OffsetMetadataManager: Clean up empty nested maps
Loading

Poem

In the warren of offsets, a new map appears,
Group, topic, partition—now every bunny cheers!
Transactions tracked with granularity so fine,
Each burrowed ID in its own little line.
With replay and cleanup, the fields are all neat—
This carrot of structure makes consistency sweet! 🥕

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java (3)

290-292: Consider initial capacity hint

While the new map is created with default capacity, we already know the upper bound equals the number of groups in the shard.
Passing an estimated initial capacity (e.g. new TimelineHashMap<>(snapshotRegistry, expectedGroupCount)) would avoid internal re‑hashing during warm‑up and complement the performance goal.


690-699: Minor micro‑optimisation opportunity

hasPendingTransactionalOffsets currently performs two nested look‑ups even when the group isn’t present.
Inlining the fast‑fail path keeps the common case cheap:

TimelineHashMap<String, TimelineHashMap<Integer, TimelineHashSet<Long>>> topics =
        openTransactionsByGroupTopicAndPartition.get(groupId);
if (topics == null) return false;
TimelineHashMap<Integer, TimelineHashSet<Long>> partitions = topics.get(topic);
return partitions != null && !partitions.getOrDefault(partition, TimelineHashSet.empty()).isEmpty();

Not critical, but consistent with the goal of shaving latency off hot paths.


1008-1012: Helper method could improve readability & symmetry

The three‑level computeIfAbsent chain is repeated in multiple places (here, plus future writes).
Encapsulating it in a private addOpenTransaction(groupId, topic, partition, producerId) helper removes duplication and lowers the cognitive load for future maintainers.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ed79212 and ba872aa.

📒 Files selected for processing (1)
  • group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java (7 hunks)
🔇 Additional comments (2)
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/OffsetMetadataManager.java (2)

201-205: 👍 Valuable fine‑grained tracking added

Introducing openTransactionsByGroupTopicAndPartition is a solid design choice that avoids repeatedly scanning every producer of a group when we only care about a single partition.
This lays the groundwork for the performance win described in the PR objective.


1067-1100: Edge‑case: stale openTransactionsByGroup entry

replayEndTransactionMarker correctly removes a producer‑id from both structures, but replay’s tombstone path (lines 1020‑1041) updates only the partition‑level map.
If that tombstone happens to clear the last pending offset for the producer, the group‑level set will still contain an orphaned producer id until the transaction eventually ends.
This can postpone group cleanup via cleanupExpiredOffsets.

If intentional, a comment explaining the lifecycle would help; otherwise consider synchronising removals in both places.

Comment on lines +661 to 674
TimelineHashMap<String, TimelineHashMap<Integer, TimelineHashSet<Long>>> openTransactionsByTopic =
openTransactionsByGroupTopicAndPartition.get(groupId);
if (openTransactionsByTopic != null) {
openTransactionsByTopic.forEach((topic, openTransactionsByPartition) -> {
openTransactionsByPartition.forEach((partition, producerIds) -> {
producerIds.forEach(producerId -> {
if (!hasCommittedOffset(groupId, topic, partition)) {
records.add(GroupCoordinatorRecordHelpers.newOffsetCommitTombstoneRecord(groupId, topic, partition));
numDeletedOffsets.getAndIncrement();
}
});
});
});
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Duplicate tombstones may be emitted for the same partition

producerIds.forEach(...) iterates once per producer id, potentially adding the same tombstone several times when multiple producers have pending offsets for the identical <group, topic, partition>.
This inflates records and over‑counts numDeletedOffsets, causing needless log traffic and skewed metrics.

- openTransactionsByPartition.forEach((partition, producerIds) -> {
-     producerIds.forEach(producerId -> {
-         if (!hasCommittedOffset(groupId, topic, partition)) {
-             records.add(GroupCoordinatorRecordHelpers
-                 .newOffsetCommitTombstoneRecord(groupId, topic, partition));
-             numDeletedOffsets.getAndIncrement();
-         }
-     });
- });
+ openTransactionsByPartition.keySet().forEach(partition -> {
+     if (!hasCommittedOffset(groupId, topic, partition)) {
+         records.add(GroupCoordinatorRecordHelpers
+             .newOffsetCommitTombstoneRecord(groupId, topic, partition));
+         numDeletedOffsets.getAndIncrement();
+     }
+ });

This preserves the original semantics while guaranteeing a single tombstone per partition.

@visz11
Copy link
Collaborator

visz11 commented Apr 24, 2025

/gemini review

Copy link

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@visz11
Copy link
Collaborator

visz11 commented Apr 24, 2025

/gemini review

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a performance improvement for fetching stable offsets by maintaining a list of pending transactions per partition. The changes seem well-structured and address the identified bottleneck. However, some areas could benefit from further clarification and potential optimization.

Summary of Findings

  • Missing null check: In replayEndTransactionMarker, there's a potential null pointer exception if openTransactionsByTopic is null after removing a topic. A null check before proceeding with further operations would enhance robustness.
  • Potential memory leak: In replay, when removing pending offset commits, the code removes partitions and topics from openTransactionsByGroupTopicAndPartition. However, it's crucial to ensure that the Offsets object associated with pendingTransactionalOffsets is also cleaned up to prevent a potential memory leak.

Merge Readiness

The pull request introduces a significant performance improvement and appears to be well-structured. However, the potential null pointer exception and memory leak should be addressed before merging. I am unable to approve this pull request, and recommend that others review and approve this code before merging. At a minimum, the high severity issues should be addressed before merging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants